<template>
  <div class="user-manage-container">
    <div class="table-operations">
      <a-button type="primary" @click="showAddModal">
        <template #icon><plus-outlined /></template>
        添加用户
      </a-button>
      <a-input-search
        v-model="searchText"
        placeholder="搜索用户名/邮箱"
        style="width: 250px; margin-left: 16px"
        @search="onSearch"
      />
    </div>

    <a-table
      :columns="columns"
      :data-source="filteredUsers"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="userID"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'userAvatar'">
          <img
            v-if="record.userAvatar"
            :src="record.userAvatar"
            alt="头像"
            style="width: 40px; height: 40px; object-fit: cover; border-radius: 50%"
          />
          <span v-else>无头像</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showEditModal(record)"><EditOutlined /> 编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除该用户吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteUser(record.userID)"
            >
              <a-button type="primary" danger><DeleteOutlined /> 删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑用户模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      :confirmLoading="confirmLoading"
    >
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="formState.password" placeholder="请输入密码（不修改可留空）" />
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select v-model:value="formState.role" placeholder="请选择角色">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="联系方式" name="contact">
          <a-input v-model:value="formState.contact" placeholder="请输入联系方式" />
        </a-form-item>
        <a-form-item label="头像" name="userAvatar">
          <a-upload
            name="image"
            :before-upload="beforeImageUpload"
            :customRequest="handleAvatarUpload"
            :show-upload-list="false"
          >
            <div v-if="uploadImageUrl">
              <img :src="uploadImageUrl" alt="头像预览" style="width: 60px; height: 60px; object-fit: cover; border-radius: 50%; border: 1px solid #d9d9d9;" />
            </div>
            <a-button v-else>
              <upload-outlined /> 上传头像
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { PlusOutlined, UploadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useUserStore } from '@/stores/userStore';
import { beforeImageUpload, uploadImage } from '@/api/utils';

const userStore = useUserStore();
const loading = computed(() => userStore.loading);
const users = computed(() => userStore.users);

const searchText = ref('');
const modalVisible = ref(false);
const modalTitle = ref('添加用户');
const confirmLoading = ref(false);
const isEdit = ref(false);
const currentId = ref(null);
const formRef = ref(null);
const uploadImageUrl = ref('');

const formState = reactive({
  username: '',
  password: '',
  role: 'user',
  email: '',
  contact: '',
  userAvatar: ''
});

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' },{ min: 3, max: 10, message: '用户名长度应在3-10个字符之间', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱格式' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
};

const columns = [
  { title: '头像', key: 'userAvatar', width: 80 },
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '角色', dataIndex: 'role', key: 'role' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  { title: '联系方式', dataIndex: 'contact', key: 'contact' },
  { title: '注册时间', dataIndex: 'registerTime', key: 'registerTime',
    customRender: ({ text }) => text ? new Date(text).toLocaleString() : '' },
  { title: '最后登录', dataIndex: 'lastLoginTime', key: 'lastLoginTime',
    customRender: ({ text }) => text ? new Date(text).toLocaleString() : '' },
  { title: '操作', key: 'action', width: 150 },
];

const filteredUsers = computed(() => {
  if (!searchText.value) return users.value;
  return users.value.filter(item =>
    (item.username && item.username.toLowerCase().includes(searchText.value.toLowerCase())) ||
    (item.email && item.email.toLowerCase().includes(searchText.value.toLowerCase()))
  );
});

const resetForm = () => {
  formState.username = '';
  formState.password = '';
  formState.role = 'user';
  formState.email = '';
  formState.contact = '';
  formState.userAvatar = '';
  uploadImageUrl.value = '';
  if (formRef.value) formRef.value.resetFields();
};

const showAddModal = () => {
  resetForm();
  isEdit.value = false;
  modalTitle.value = '添加用户';
  modalVisible.value = true;
};

const showEditModal = (record) => {
  isEdit.value = true;
  currentId.value = record.userID;
  modalTitle.value = '编辑用户';
  Object.assign(formState, {
    username: record.username,
    password: '',
    role: record.role,
    email: record.email,
    contact: record.contact,
    userAvatar: record.userAvatar || ''
  });
  uploadImageUrl.value = record.userAvatar || '';
  modalVisible.value = true;
  nextTick(() => {
    formRef.value && formRef.value.setFieldsValue(formState);
  });
};

const handleModalOk = () => {
  formRef.value.validate().then(async () => {
    if (!isEdit.value && !formState.password) {
      message.error('密码不能为空');
      return;
    }
    confirmLoading.value = true;
    try {
      if (isEdit.value) {
        await userStore.updateUser(currentId.value, { ...formState });
        message.success('用户信息更新成功');
      } else {
        await userStore.addUser({ ...formState });
        message.success('用户添加成功');
      }
      modalVisible.value = false;
      resetForm();
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      confirmLoading.value = false;
    }
  }).catch(error => {
    console.log('表单验证失败:', error);
    message.warning('表单验证失败', error);
  });
};

const deleteUser = async (id) => {
  try {
    await userStore.deleteUser(id);
    message.success('用户删除成功');
  } catch (error) {
    message.error('删除失败: ' + error.message);
  }
};

const onSearch = () => {
  // 搜索功能已通过计算属性实现
};

const handleAvatarUpload = async ({ file, onSuccess, onError }) => {
  try {
    const url = await uploadImage({ file });
    uploadImageUrl.value = url;
    formState.userAvatar = url;
    message.success('头像上传成功');
    onSuccess();
  } catch (error) {
    onError();
    message.error('头像上传失败');
  }
};

onMounted(() => {
  userStore.fetchUsers();
});
</script>

<style scoped>
.user-manage-container {
  width: 100%;
  min-height: 100vh;
  padding: 24px;
  background: #f5f7fa;
}
.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style> 